package application.server.jms;

import java.util.Properties;

import javax.naming.*;
import javax.jms.*;

public class MyProducer {
	
	private static MyProducer _instance = null;
	private Connection _con;
	private Destination _dest;
	
	private MyProducer() throws NamingException, JMSException{
		connect();
	}
	
	public static MyProducer getInstance() throws NamingException, JMSException{
		if (_instance == null){
			return new MyProducer();
		} else {
			return _instance;
		}
	}
	
	private void connect() throws NamingException, JMSException {
		InitialContext ctx = new InitialContext();
		// Get the ConnectionFactory by JNDI name
		QueueConnectionFactory cf =
		(QueueConnectionFactory)ctx.lookup("LibManQueueFactory");

		// get the Destination used to send the message by JNDI name
		_dest = (Destination)ctx.lookup("LibManQueue");
		// Create a connection
		_con = cf.createConnection();
	}
	
	public void sendMessage(String message) throws JMSException{
		// create a JMS session
		Session sess = _con.createSession(false, Session.AUTO_ACKNOWLEDGE);
		// Create a MessageProducer and some Message with the session

		MessageProducer prod = sess.createProducer(_dest);		
		Message msg = sess.createTextMessage(message);
		// send the message to the destination
		prod.send(msg);
	}
	
	public void disconnect () throws JMSException{
		_con.close();
		System.out.println("Connection closed");
	}
	
}
